package com.wm.blog_admin.interceptor;

import com.wm.blog_common.constatnt.CommonConstant;
import com.wm.blog_common.context.AdminBaseContextHandler;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *@ClassName TokenInterceptor
 *@Description
 *@Author 半卷流年
 *@Date 2020/9/27 17:52
 */
@Component
public class TokenInterceptor extends HandlerInterceptorAdapter {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        this.currentInfo(request);
        return true;

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //threadLocal移除数据,防止内存泄露
        AdminBaseContextHandler.remove();
        super.afterCompletion(request, response, handler, ex);
    }

    /**
     * 当前登录人的id
     * @param request
     * @return
     */
    private void currentInfo(HttpServletRequest request){
        String idHeader = request.getHeader(CommonConstant.ADMIN);
        long id = StringUtils.isNotEmpty(idHeader) ? Long.parseLong(idHeader) : -1L;
        String nameHeader = request.getHeader(CommonConstant.ADMIN_NAME);
        String name = StringUtils.isNotEmpty(nameHeader) ? nameHeader:null;
        AdminBaseContextHandler.setUserNameAndUserId(name,id);
    }


    /**
     * 当前的请求头
     * @param request
     * @return
     */
    private String currentAuthorization(HttpServletRequest request){
        return request.getHeader(CommonConstant.AMIND_Authorization);
    }

}
